/**
 * Copyright (c) 2016-2019 优博信息科技 All rights reserved.
 *
 * https://www.jnyoubo.com
 *
 * 版权所有，侵权必究！
 */

package com.youbo.controller;
import com.youbo.common.utils.*;
import com.youbo.config.UserConfig;
import com.youbo.entity.BrdaEntity;
import com.youbo.form.*;
import com.youbo.service.ApiV1Service;
import com.youbo.service.BrdaService;
import com.youbo.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * his 接口
 *
 * @author macy
 */
@RestController
@RequestMapping("/v1/api")
@Api(tags="院内使用接口文档")
public class InsideV1Controller {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserConfig userConfig;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ApiV1Service apiV1Service;
    @Autowired
    private BrdaService brdaService;

    /**
     * 测试
     * @return
     */
    @RequestMapping(value = "mytest",method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation("公共提交查询接口")
    public Object mytest(@RequestBody(required = false) Pform p,@RequestParam(value = "m",required = false) Pform m){

        logger.debug("-----------------------------debug-----------------------------");
        String str="[{\n" +
                "                    \"outTradeNo\": \"DRGH_ymzyy_1803052\",\n" +
                "                    \"sourceOutTradeNo\": \"DRGH_ymzyy_1803052\",\n" +
                "                    \"refundOrderNo\": null,\n" +
                "                    \"payTime\": \"2018-03-05 14:02:06\",\n" +
                "                    \"stateDes\": \"已退款\",\n" +
                "                    \"amount\": 0.01,\n" +
                "                    \"customName\": \"马金花\",\n" +
                "                    \"payerName\": \"沈振华\",\n" +
                "                    \"transactionId\": \"29358903jfiu98wru934\"\n" +
                "                }]";
        return R.ok().putData(JsonTools.string2Obj(str, List.class));
    }




    /**
     * 公共提交查询接口
     * @param p.path=/xxx/xxx/xx 或者 m.path=/xxx/xxx/xx
     * @return
     */
    @RequestMapping(value = "send",method = {RequestMethod.POST})
    @ApiOperation("公共提交查询接口")
    public Object send(@RequestBody(required = false) Pform p,@RequestParam(value = "m",required = false) Pform m){
        String json="{}";
        String path="";
        if(m!=null){
            json=JsonTools.obj2String(m);
            path=m.getString("path");
        }
        if(p!=null){
            json=JsonTools.obj2String(p);
            path=p.getString("path");
        }
        return HttpUtils.post(userConfig.getServiceIp()+path,json);
    }




    /**
     * 对账
     */

    /**
     * 查询院内订单
     * @return
     */
    @RequestMapping(value = "myorder",method = {RequestMethod.POST})
    @ApiOperation("查询院内订单")
    public Object myorder(@RequestBody(required = false) Pform p){
        String json="{}";
        if(p!=null){
            json=JsonTools.obj2String(p);
        }

        List<HashMap> list=orderService.queryMyOrder(p);
        if(null==list){
            return R.error(R.ERROR3,"暂无数据");
        }
        if(list.size()<=0){
            return R.error(R.ERROR3,"暂无数据");
        }

        return R.ok("查询成功").putData(list);
    }

    /**
     * 对账
     */

    /**
     * 指定时间段内交易信息查询
     * @return
     */
    @RequestMapping(value = "reconciliationQuery",method = {RequestMethod.POST})
    @ApiOperation("指定时间段内交易信息查询")
    public Object reconciliationQuery(@RequestBody(required = false) Pform p,@RequestParam(value = "m",required = false) Pform m){
        String json="{}";
        if(m!=null){
            json=JsonTools.obj2String(m);
        }
        if(p!=null){
            json=JsonTools.obj2String(p);
        }
        return HttpUtils.post(userConfig.getServiceIp()+"/prefront/reconciliation/query",json);
    }


    /**
     * 根据院内退款单号查询退款记录
     * @return
     */
    @RequestMapping(value = "queryByHospitalRefundNo",method = {RequestMethod.POST})
    @ApiOperation("根据院内退款单号查询退款记录 ")
    public Object queryByHospitalRefundNo(@RequestBody(required = false) Pform p,@RequestParam(value = "m",required = false) Pform m){
        String json="{}";
        if(m!=null){
            json=JsonTools.obj2String(m);
        }
        if(p!=null){
            json=JsonTools.obj2String(p);
        }
        return HttpUtils.post(userConfig.getServiceIp()+"/prefront/reconciliation/queryByHospitalRefundNo",json);
    }


    /**
     * 根据 卡号 查询病人信息 不存在就创建 返回
     * @return
     */
    @RequestMapping(value = "queryBrSaveUpdate",method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation("根据 卡号 查询病人信息 不存在就创建 返回")
    public Object queryBrSaveUpdate(@RequestParam(required = false) String medicalCardNumber,@RequestBody(required = false) Pform p){
        if(medicalCardNumber==null){
            if(null==p||null==p.getString("medicalCardNumber")){
                return R.error(R.ERROR3,"卡号不能为空");
            }
        }
        if(null==medicalCardNumber){
            medicalCardNumber=p.getString("medicalCardNumber");
        }
        if(null==medicalCardNumber){
            return R.error(R.ERROR3,"卡号不能为空");
        }


        BrdaEntity brdaEntity=brdaService.queryMedicalCardNumber(medicalCardNumber);
        if(null==brdaEntity){
            String response=apiV1Service.getPatientInfo(medicalCardNumber);
            if(null==response){
                logger.error("查询失败:"+response);
                return R.ok(R.ERROR3,"根据电子卡号查询用户信息失败");
            }
            R res=JsonTools.string2Obj(response,R.class);
            if(!res.getSuccess()){
                logger.error("同步信息错误:"+response);
                return R.ok(R.ERROR3,"根据电子卡号查询用户信息失败");
            }
            CreateCardForm createCardForm=JsonTools.string2Obj(JsonTools.obj2String(res.getData()),CreateCardForm.class);
            if(null!=createCardForm.getIdcard()&&!createCardForm.getIdcard().equals("")){
                //检查是否存在此用户
                brdaEntity=brdaService.queryIdCardNo(createCardForm.getIdcard());
                if(null!=brdaEntity){
                    brdaService.updateBrzhCardNumbrer(brdaEntity.getBrid(),createCardForm.getMedicalCardNumber());
                }else {
                    //创建新的 病人档案
                    if(!brdaService.saveBrdn(createCardForm)){
                        return R.error(R.ERROR3,"创建失败");
                    }
                }
            }else{
                //创建新的 病人档案
                if(!brdaService.saveBrdn(createCardForm)){
                    return R.error(R.ERROR3,"创建失败");
                }
            }
        }

       brdaEntity=brdaService.queryMedicalCardNumber(medicalCardNumber);

       return R.ok().putData(brdaEntity);
    }


    /**
     * 签名
     * @return
     */
    @RequestMapping(value = "sign",method = {RequestMethod.POST,RequestMethod.GET})
    @ApiOperation("签名 ")
    public Object sign(
            @RequestBody(required = false) Pform p,
            @RequestParam(value = "appid",required = false) String appid,
            @RequestParam(value = "time",required = false) String time,
            @RequestParam(value = "nonce_str",required = false) String nonce_str,
            @RequestParam(value = "key",required = false) String key){

        String data="";//utj77obgueh3a5jx0olx&1608087415&cYqippRZdx
        if(null!=p){
            data=p.getString("appid")+"&"+p.getString("time")+"&"+p.getString("nonce_str");
            key=p.getString("key");
        }
        if(null!=appid&&null!=time&&null!=nonce_str){
            data=appid+"&"+time+"&"+nonce_str;
        }

        return R.ok().putData(Base64Tools.genHMAC(data,key));
    }


}
